package com.sitech.ibnms.util.upload;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TelnetNotificationHandler;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;

public class TelnetThread implements Runnable, TelnetNotificationHandler,
		RomoteController {

	private TelnetClient tc = null;
	private OutputStream outstr = null;
	private InputStream instr = null;
	// 是否认证完毕
	private boolean autorized = false;
	private String host_ip = null;
	private int host_port = 23;
	private String login_id = null;
	private String password = null;
	private String keywords = null;
	// 存放命令执行结果
	private StringBuffer result = new StringBuffer();
	// 执行结束标志
	private boolean endExecute = false;

	public boolean isRunning(String keywords, String username) {
		this.keywords = keywords;
		String command = "ps -ef | grep " + this.keywords;
		if (username != null && !"".equals(username)) {
			command += " | grep " + username;
		}
		command = command + " | grep -v grep";
		this.doCommand(command);
		String result = this.getResult();
		// result = result.replaceAll("grep " + this.keywords, " ");
		if (result != null && result.indexOf(this.keywords) != -1) {
			return true;
		} else {
			return false;
		}

	}
	
	public boolean isRunning(String keywords) {
		this.keywords = keywords;
		this.doCommand("ps -ef | grep "+this.keywords);
		String result = this.getResult();
		result=result.replaceAll("grep "+this.keywords, " ");
		if(result!=null&&result.indexOf(this.keywords)!=-1){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 构造方法
	 * 
	 * @param host_ip
	 * @param port
	 * @param login_id
	 * @param password
	 */
	public TelnetThread(String host_ip, int port, String login_id,
			String password) {
		this.host_ip = host_ip;
		this.host_port = port;
		this.login_id = login_id;
		this.password = password;
	}

	public void initial() {
		try {
			tc = new TelnetClient();
			TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler(
					"VT100", false, false, true, false);
			EchoOptionHandler echoopt = new EchoOptionHandler(true, false,
					true, false);
			SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true,
					true, true, true);
			try {
				tc.addOptionHandler(ttopt);
				tc.addOptionHandler(echoopt);
				tc.addOptionHandler(gaopt);
			} catch (InvalidTelnetOptionException e) {
				System.err.println("Error registering option handlers: "
						+ e.getMessage());
			}
			tc.connect(this.host_ip, this.host_port);
			tc.setSoTimeout(120000);
			//tc.setSoTimeout(120);
			outstr = tc.getOutputStream();
			instr = tc.getInputStream();
		} catch (Exception e) {
			System.out.println("telnet创建连接失败");
			return;
		}

		int login_times = 0;
		String s = this.getResult();
		if (!this.autorized) {
			return;
		}
		while ((s.endsWith("login: ") || s.endsWith("login:")
				|| s.endsWith("Password: ") || s.endsWith("Password:"))
				&& tc.isConnected()) {
			if (s.endsWith("login: ") || s.endsWith("login:")) {
				this.doCommand(this.login_id);
				s = this.getResult();
				login_times += 1;
				if (login_times > 2) {
					System.out.println("用户名或者密码错误！！！");
					this.autorized = false;
					try {
						tc.disconnect();
						return;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			if (s.endsWith("Password: ") || s.endsWith("Password:")) {
				this.doCommand(this.password);
				s = this.getResult();
			}
		}
		this.autorized = true;
	}

	public void doCommand(String command) {
		if (tc == null || !tc.isConnected()) {
			System.out.println("没有与主机连接，无法执行命令！");
			return;
		}
		if (this.endExecute == false) {
			System.out.print("命令还没有执行完，请稍候执行该命令！");
			return;
		}
		if (this.outstr == null) {
			System.out.println("没有输出流到主机，无法执行命令！");
			return;
		}
		String shell = "";
		if (!command.endsWith("\n")) {
			shell = command + "\n";
		} else {
			shell = command;
		}
		try {
			this.result = new StringBuffer();
			this.endExecute = false;
			// 执行命令
			outstr.write(shell.getBytes());
			outstr.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getResult() {
		if (tc == null || !tc.isConnected()) {
			System.out.println("没有连接主机!");
			return null;
		}
		if (instr == null) {
			System.out.println("输入流错误！");
			return null;
		}
		if (this.endExecute == true) {
			System.out.println("没有命令执行！！！");
			return null;
		}

		try {
			char[] chabuff = new char[1024];
			int ret_read = 0;
			InputStreamReader inr = new InputStreamReader(instr);
			do {
				ret_read = inr.read(chabuff);
				if (ret_read > 0) {

					String ss = new String(chabuff, 0, ret_read);
					this.result.append(ss);
					String rs = result.toString().toString();
					if (rs.endsWith(">") || rs.endsWith("$")
							|| rs.endsWith("]") || rs.endsWith(">")
							|| rs.endsWith("$ ")
							|| result.toString().endsWith("login: ")
							|| result.toString().endsWith("login:")
							|| result.toString().endsWith("Password: ")
							|| result.toString().endsWith("Password:")) {
						break;
					}

				}
			} while (ret_read >= 0);
			this.autorized = true;
		} catch (Exception e) {
			this.autorized = false;
			e.printStackTrace();
		} finally {

		}
		this.endExecute = true;
		return this.result.toString();
	}

	public void receivedNegotiation(int negotiation_code, int option_code) {
	}

	public void run() {
		this.initial();
		try {

			byte[] buff = new byte[1024];
			int ret_read = 0;
			do {
				ret_read = System.in.read(buff);
				if (ret_read > 0) {
					if (new String(buff, 0, ret_read).startsWith("quit")) {
						tc.disconnect();
						return;
					} else {
						System.out.println("#" + new String(buff, 0, ret_read)
								+ "#");
					}
					this.doCommand(new String(buff, 0, ret_read));
					this.getResult();
				}
			} while (ret_read > 0);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 关闭连接
	 * 
	 */
	public void close() {
		try {
			byte b = 0x03;
			outstr.write(b);
			outstr.flush();
			this.doCommand("exit");
			if (tc != null && tc.isConnected())
				tc.disconnect();
			tc = null;
		} catch (Exception e) {
			e.printStackTrace();

			try {
				tc.disconnect();
			} catch (Exception e1) {
				e1.printStackTrace();
			}

		}

	}

	public boolean isAuthorized() {
		return this.autorized;
	}

	public boolean isExistDir(String dir) {
		boolean success = true;
		this.doCommand("cd " + dir);

		if (this.getResult().indexOf(dir + ":  not found") != -1) {
			success = false;
		}
		return success;
	}

	public boolean getResultAsString(String targetString) {
		// TODO Auto-generated method stub
		if (tc == null || !tc.isConnected()) {
			System.out.println("没有连接主机!");
			return false;
		}
		if (instr == null) {
			System.out.println("输入流错误！");
			return false;
		}
		if (this.endExecute == true) {
			System.out.println("没有命令执行！！！");
			return false;
		}

		try {
			char[] chabuff = new char[1024];
			int ret_read = 0;
			InputStreamReader inr = new InputStreamReader(instr);
			do {
				ret_read = inr.read(chabuff);
				if (ret_read > 0) {
					String ss = new String(chabuff, 0, ret_read);
					System.out.print(new String(chabuff, 0, ret_read));
					this.result.append(ss);
					String rs = result.toString().toString();
					if (rs.endsWith(">") || rs.endsWith("$")
							|| rs.endsWith("]") || rs.endsWith(">")
							|| rs.endsWith("$ ")
							|| result.toString().endsWith("login: ")
							|| result.toString().endsWith("Password: ")
							|| result.toString().endsWith("Password:")) {
						break;
					}

				}
			} while (ret_read >= 0);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		this.endExecute = true;
		if (this.result.toString().indexOf(targetString) != -1) {
			return true;
		} else {
			return false;
		}

	}

	public int childCountOfDir(String dir) {
		int count = 0;
		try {
			if (this.isExistDir(dir)) {
				doCommand("cd " + dir + ";ls -l | wc -l");
				String s = null;
				s = getResult();
				String[] s1 = s.split("\n");
				if (s1 != null) {
					count = new Integer(s1[1].trim()).intValue() - 1;
				}
			} else {
				return -1;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
		return count;
	}

	public boolean createDir(String dir) {
		boolean isExist = false;
		if (dir != null && !dir.trim().equals("") && this.isExistDir(dir)) {
			isExist = true;
		}
		// 逐层分析目录，如果没有则创建.
		if (dir != null && !dir.trim().equals("") && !this.isExistDir(dir)) {
			String[] split_dir = dir.split("/");
			for (int i = 0; i < split_dir.length; i++) {
				String path = "";
				for (int j = 0; j <= i; j++) {
					if (split_dir[j] != null && !split_dir[j].equals("")) {
						path += "/" + split_dir[j];
					}
				}
				if (path != null && !path.equals("")) {
					if (!this.isExistDir(path)) {
						this.doCommand("mkdir " + path);
						this.getResult();
					}
					if (!this.isExistDir(path)) {
						return false;
					}
				}
			}
			if (this.isExistDir(dir)) {
				isExist = true;
			}
		}
		return isExist;
	}
	
	public boolean isUsed(int port) {
		this.doCommand("netstat -an | grep -v TIME_WAIT | awk '{print $4}' | grep " + port + "");
		String result = this.getResult();
		if (result != null && result.indexOf("" + port) >= 0) {
			return true;
		}
		
		return false;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TelnetThread tel = new TelnetThread("172.21.1.68", 23, "bnmsapp",
				"bnmsapp");
		tel.initial();
		boolean result = tel.isRunning("Djavax.kkk.builder.initial",
				"bnmsapp");
		System.out.println(result);
		tel.close();
	}
}
